package com.neusoft.tmall.security;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.URLUtil;
import com.neusoft.tmall.config.IgnoreUrlsConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.FilterInvocation;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import java.util.Collection;
import java.util.Iterator;

/**
 * 比较当前用户的权限
 * @Author: duan
 * @Date: Create in 21:35 2020/7/26
 */
public class DynamicAccessDecisionVoter implements AccessDecisionVoter {

    @Autowired
    private IgnoreUrlsConfig ignoreUrlsConfig;

    public DynamicAccessDecisionVoter(IgnoreUrlsConfig ignoreUrlsConfig) {
        this.ignoreUrlsConfig = ignoreUrlsConfig;
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }

    @Override
    public boolean supports(Class clazz) {
        return true;
    }

    @Override
    public int vote(Authentication authentication, Object object, Collection collection) {
        //当接口未被配置资源时直接放行
        if (CollUtil.isEmpty(collection)) {
            return ACCESS_DENIED;
        }
        //处理白名单
        //获取当前访问的路径
        String url = ((FilterInvocation) object).getRequestUrl();
        String path = URLUtil.getPath(url);
        PathMatcher pathMatcher = new AntPathMatcher();
        for(String item: ignoreUrlsConfig.getUrls()){
            if (pathMatcher.match(item, path)) {
                return ACCESS_GRANTED;
            }
        }

        Iterator<ConfigAttribute> iterator = collection.iterator();
        while (iterator.hasNext()) {
            ConfigAttribute configAttribute = iterator.next();
            //将访问所需资源或用户拥有资源进行比对
            String needAuthority = configAttribute.getAttribute();
            for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
                if (needAuthority.trim().equals(grantedAuthority.getAuthority())) {
                    return ACCESS_GRANTED;
                }
            }
        }
        throw new AccessDeniedException("抱歉，您没有访问权限");
    }
}

